package com.common.transparent.module;

import android.Manifest;
import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

/**
 * Created by wen on 2017/9/21.
 */

public class CameraPreviewView extends SurfaceView implements SurfaceHolder.Callback {

    private Camera mCamera;
    private Camera.CameraInfo mCameraInfo;

    // 相机方向
    private int mRotation;

    private SurfaceHolder mHolder;

    private int mPreviewHeight = -1;
    private int mPreviewWidth = -1;

    // 外部调用一次，表示已经有权限了
    private boolean hasCameraPermission;
    // onSurfaceCreated 是否调用
    private boolean isAlreadyCreate;

    public CameraPreviewView(Context context) {
        super(context);
        init();
    }

    public CameraPreviewView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        hasCameraPermission = PermissionManager.checkPermission(getContext(), Manifest.permission.CAMERA);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getWidthMeasureSpec(widthMeasureSpec, heightMeasureSpec),
                getHeightMeasureSpec(widthMeasureSpec, heightMeasureSpec));
    }

    public int getWidthMeasureSpec(final int widthMeasureSpec, final int heightMeasureSpec) {
        if (mPreviewHeight >= 0) {
            final int width = MeasureSpec.getSize(widthMeasureSpec);
            return MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
        } else {
            return widthMeasureSpec;
        }
    }

    public int getHeightMeasureSpec(final int widthMeasureSpec, final int heightMeasureSpec) {
        if (mPreviewHeight >= 0) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = width * mPreviewHeight / mPreviewWidth;

            return MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        } else {
            return heightMeasureSpec;
        }
    }

    /**
     * 通过手机的方向，保存相应的预览大小
     *
     * @param size
     * @param orientation
     */
    public void setSize(Camera.Size size, int orientation) {
        switch (orientation) {
            case 0:
            case 180:
                mPreviewWidth = Math.max(size.width, size.height);
                mPreviewHeight = Math.min(size.width, size.height);
                break;
            case 90:
            case 270:
            default:
                mPreviewWidth = Math.min(size.width, size.height);
                mPreviewHeight = Math.max(size.width, size.height);
        }
    }

    public void initCamera() {
        if (mCamera == null)
            mCamera = Camera.open();

        mCamera.stopPreview();

        mCameraInfo = CameraUtil.getBackCameraInfo();
        // 设置方向
        mRotation = CameraUtil.setCameraDisplayOrientation(getContext(), mCameraInfo, mCamera);
        mCamera.setDisplayOrientation(mRotation);

        Camera.Size size = CameraUtil.getPreviewSize(getContext(), mCamera);
        setSize(size, mRotation);

        Camera.Parameters parameters = mCamera.getParameters();
        // 自动对焦
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        mCamera.setParameters(parameters);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        isAlreadyCreate = true;
        if (hasCameraPermission)
            startPreviewInner();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        isAlreadyCreate = true;
        if (hasCameraPermission) {
            startPreviewInner();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        stopPreview();
    }


    private void startPreviewInner() {
        initCamera();

        if (isAlreadyCreate)
            realPreview();
        requestLayout();
    }

    private void realPreview() {
        try {
            mCamera.setPreviewDisplay(mHolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mCamera.startPreview();
    }

    public void startPreview() {
        // 外部主动调用，表示有权限
        hasCameraPermission = true;
        if (isAlreadyCreate)
            startPreviewInner();
    }

    public void stopPreview() {
        if (mCamera == null) {
            return;
        }
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;

        isAlreadyCreate = false;
    }
}
